package com.tencent.wxcloudrun.vpnmanagement.tools;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
@ConfigurationProperties(prefix = "ttframe.jwt.config")
public class JwtUtil {
    /*
    * 密钥
    * */
    private String secretKey;
    /*
    * 超时时间，默认7天
    * */
    private long expires=60*60*24*7;

    public String getSecretKey() {
        return secretKey;
    }

    public void setSecretKey(String secretKey) {
        this.secretKey = secretKey;
    }

    public long getExpires() {
        return expires;
    }

    public void setExpires(long expires) {
        this.expires = expires;
    }

    public  String createJwt(String openId,String subject,String phoneNum,Boolean isLogin){
        long nowMillis=System.currentTimeMillis();
        Date now= new Date(nowMillis);

        JwtBuilder builder= Jwts.builder().setId(openId)//用户ID
                .setSubject(subject)//用户名
                .setIssuedAt(now)//签发时间
                .signWith(SignatureAlgorithm.HS256, secretKey)//密钥
                .claim("isLogin",isLogin)
                .claim("phoneNum",phoneNum);
        if(expires>0) {
            builder.setExpiration(new Date(nowMillis + expires * 1000));
        }
        return builder.compact();
    }

    public Claims parseJWT(String  jwtToken){
        return Jwts.parser().setSigningKey(secretKey)
                .parseClaimsJws(jwtToken).getBody();
    }
}
